<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace ckeeper\utils;


use Swoole\Coroutine\System;

class MacAddress
{

    private static array $returnArray = []; // 返回带有MAC地址的字串数组
    private static string $macAddr = '';

    /**
     * @return array
     */
    private static function forWindows()
    {
        self::$returnArray = System::exec("ipconfig /all");
        if (self::$returnArray)
            return self::$returnArray;
        else {
            $ipconfig = $_SERVER["WINDIR"] . "\system32\ipconfig.exe";
            if (is_file($ipconfig)) {
                self::$returnArray = System::exec($ipconfig . " /all");
            } else {
                self::$returnArray = System::exec($_SERVER["WINDIR"] . "\system\ipconfig.exe /all");
            }
            return self::$returnArray;
        }
    }


    /**
     * @return array|mixed
     */
    private static function forLinux()
    {
        self::$returnArray = System::exec('ifconfig -a');
        return self::$returnArray;
    }


    /**
     * @param $osType
     * @return mixed|string
     */
    public static function get($osType)
    {
        if (empty(self::$returnArray)) {
            switch (strtolower($osType)) {
                case "linux":
                    self::forLinux();
                    break;
                case "solaris":
                    break;
                case "unix":
                    break;
                case "aix":
                    break;
                default:
                    self::forWindows();
                    break;
            }
        }

        $temp_array = array();
        foreach (self::$returnArray as $value) {
            if (preg_match("/[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f][:-]" . "[0-9a-f][0-9a-f]/i", $value, $temp_array)) {
                self::$macAddr = $temp_array[0];
                break;
            }
        }
        unset($temp_array);
        return self::$macAddr;
    }

}
